<template>
  <div class="point-of-raw">
    <div ref="chart" class="thechart"></div>
    <button @click="go_up()">↑</button>
    <button @click="go_down()">↓</button>
    <button @click="go_left()">←</button>
    <button @click="go_right()">→</button>
    <button @click="download_now_json()">Download</button>
  </div>
</template>
<script>
import axios from "axios";
import randomcolor from "randomcolor";
import Color from "color";
import * as jsonBeautify from "json-beautify";
let clipboardjs = require("clipboard");
let localforage = require("localforage");

const libDP = require("../lib/Douglas-Peucker");
import * as echarts from "echarts";
import { round, min, max, flatten, map } from "lodash";
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "https://qimage.owhat.cn/prod/master/image/e998aac9-462c-46ce-9c96-0e9506af0da5#Sanhok_Main_High_Res.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};
const MAP_NAME = "Sanhok";
const MapGameLength = MAP_LENGTH_CENTIMETERS[MAP_NAME];
const MapSize = 1000;
let _scale = MapSize / MapGameLength;
let the_chart = null;

let selected_indexes = [];
let the_data = null;
let chart = null;

var funDownload = function(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
};

export default {
  name: "TSNEzhuanhuan",
  data() {
    return {};
  },
  async mounted() {
    let vue = this;
    let ele = this.$refs["chart"];
    chart = echarts.init(ele, "", {
      renderer: "canvas"
    });
    let grid_sssssize = 450;
    let gridPosition = {
      left: 30,
      // right: 10,
      // bottom: 300,
      top: 10,
      width: grid_sssssize,
      height: grid_sssssize
    };
    let p_data = await this.ajaxDataPromise;
    the_data = p_data;
    // localStorage['data'] = JSON.stringify(p_data)
    // localforage.config({
    //   name: "Hipster PDA App"
    // });

    let series = await this.getSeries();
    let optBrush = {
      brushLink: series
        .map((e, i) => {
          if (e._needBrush) return i;
          else return -1;
        })
        .filter(e => e > -1),
      xAxisIndex: [0, 1],
      yAxisIndex: [0, 1],
      toolbox: ["rect", "polygon", "keep", "clear", "lineX", "lineY"],
      inBrush: {
        opacity: 1,
        color: "red",
        colorSaturation: 1
      },
      outOfBrush: {
        opacity: 0.3,
        symbolSize: 5,
        color: "rgba(0,0,0,0.3)"
        // colorSaturation: 0
      },
      brushStyle: {
        borderWidth: 1,
        color: "rgba(0,0,180,0.2)",
        borderColor: "rgba(120,140,180,0.8)"
      },
      throttleType: "debounce",
      throttleDelay: 1
    };
    chart.setOption({
      backgroundColor: "transparent" || "white",
      color: ["#c23531", "#91c7ae", "#dd8668"],
      brush: optBrush,
      tooltip: {
        trigger: "item"
      },
      dataZoom: [
        { type: "inside", xAxisIndex: [0], filterMode: "none" },
        { type: "inside", yAxisIndex: [0], filterMode: "none" }
      ],
      grid: [
        {
          ...gridPosition,
          show: true,
          backgroundColor: "transparent"
        }
      ],
      xAxis: [
        {
          type: "value",
          splitLine: {
            // show: false
          },
          axisLine: {
            // show: false
          },
          axisLabel: {
            // show: false
          },
          axisTick: {
            // show: false
          }
        }
      ],
      yAxis: [
        {
          type: "value",
          max:50,
          splitLine: {
            // show: false
          },
          axisLine: {
            // show: false
          },
          axisLabel: {
            // show: false
          },
          axisTick: {
            // show: false
          }
        }
      ],
      series: [...series]
    });
    chart.on("brushselected", async params => {
      // debugger;
      if (
        params.batch &&
        params.batch[0] &&
        params.batch[0].selected.length &&
        params.batch[0].selected[0].dataIndex.length
      ) {
        //
        // debugger
        selected_indexes = params.batch[0].selected[0].dataIndex;
      } else {
        selected_indexes = [];
      }
      // debugger
    });
  },
  computed: {
    ajaxDataPromise() {
      return this.getData();
    }
  },
  methods: {
    getData() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/f7115fba-1803-4e3d-86ec-aad5442e2a2d";
      link =
        "https://qimage.owhat.cn/prod/master/image/6341fedf-6be0-4ceb-ba35-ce9031e9829a";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxKuangxuan() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/4273acab-ade1-4810-8858-f9889db95596";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    async getSeries() {
      let data0323 = await this.ajaxDataPromise;
      let tsneSeries = {
        type: "scatter",
        id: "tsne",
        name: "tsne",
        _needBrush: true,
        data: data0323.map(e => [e.tsne[0], e.tsne[1], e.ranking, e.pois]),
        xAxisIndex: 0,
        yAxisIndex: 0,
        itemStyle: {
          borderWidth: 0,
          borderColor: "white",
          color: params => {
            // debugger
            // if (params.data[3].includes("Camp Bravo")) {
            //   return "blue";
            // }
            return "red";
            if (params.value[2] == 1) {
              return "red";
            }
            return "rgba(0,0,0,1)";
          },
          opacity: 0.5
        },
        symbolSize: 5
      };
      let data_kuangxuan = await this.ajaxKuangxuan();
      let polygon_series = data_kuangxuan.map(k => {
        let mined = min(flatten(k.points));
        let maxed = max(flatten(k.points));
        // debugger;
        return {
          type: "custom",
          data: [[mined, k.points.length]],
          // // clip: true,
          renderItem: (params, api) => {
            // debugger
            // let dataIndex = params.dataIndex;
            let data = k.points;
            // console.log(data.points);
            // ""
            debugger;
            return {
              type: "group",
              children: [
                {
                  type: "polygon",
                  shape: {
                    points: data.map(p => api.coord(p))
                  },
                  style: {
                    stroke: "rgba(0,0,255,0.5)",
                    lineWidth: 2,
                    fill: "rgba(202,202,235,0.5)"
                  }
                }
              ]
            };
          }
        };
      });
      // };
      // debugger
      return [
        tsneSeries,
        ...polygon_series
      ];
    },
    go_up() {
      if (selected_indexes.length && the_data) {
        for (let i of selected_indexes) {
          the_data[i].tsne[1] += 1;
          console.log(i, the_data[i].tsne);
        }
        this.reset_series();
      }
    },
    go_down() {
      if (selected_indexes.length && the_data) {
        for (let i of selected_indexes) {
          the_data[i].tsne[1] -= 1;
          console.log(i, the_data[i].tsne);
        }
        this.reset_series();
      }
    },
    go_right() {
      if (selected_indexes.length && the_data) {
        for (let i of selected_indexes) {
          the_data[i].tsne[0] += 1;
          console.log(i, the_data[i].tsne);
        }
        this.reset_series();
      }
    },
    go_left() {
      if (selected_indexes.length && the_data) {
        for (let i of selected_indexes) {
          the_data[i].tsne[0] -= 1;
          console.log(i, the_data[i].tsne);
        }
        this.reset_series();
      }
    },
    reset_series() {
      let series_data = the_data.map(e => [e.tsne[0], e.tsne[1]]);
      // debugger;
      chart.setOption({
        series: [
          {
            id: "tsne",
            data: series_data
          }
        ]
      });
    },
    download_now_json() {
      funDownload(JSON.stringify(the_data), "xxx.json");
    }
  }
};
</script>
<style lang="less" scoped>
.thechart {
  width: 500px;
  height: 500px;
}
</style>